package com.blog.zip.controller;

import com.blog.zip.bean.RespBean;
import com.blog.zip.bean.SiteLink;
import com.blog.zip.mapper.SiteLinkMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
public class LinkController {
    @Autowired
    private SiteLinkMapper siteLinkMapper;

    @PostMapping("/link/add")
    public RespBean addLink(@RequestBody SiteLink link) {
        // 使用getLink()查找是否存在相同的链接 使用动态sql
        List<SiteLink> list = new ArrayList<>();
        SiteLink linkParams = new SiteLink();
        linkParams.setUrl(link.getUrl());
        list = siteLinkMapper.getLink(linkParams);
        Map<String, Object> map = new HashMap<>();
        if (list.size() != 0) {
            return new RespBean(301, 200, "add repeat");
        } else {
            siteLinkMapper.addLink(link);
            return new RespBean(1, 200, "add success");
        }
    }

    @PostMapping("/link/update")
    public RespBean updateLink(@RequestBody SiteLink link) {
        siteLinkMapper.updateLink(link);
        return new RespBean(200, "update success");
    }

    @PostMapping("/link/delete")
    public RespBean deleteLink(@RequestBody Map<String,Object> m) {
        siteLinkMapper.deleteLink((Integer) m.get("id"));
        return new RespBean(200, "delete success");
    }

    /**
     * 执行分页操作 默认第一页 每页10条
     * sql语句 select * from wy_laptop limit ? , ? 参数1 start = (page - 1) * pageSize 参数2 pageSize
     * 友情链接的获取
     *
     * @param siteLink
     * @return
     */
    @PostMapping("/link/get")
    public Map<String, Object> getLink(@RequestBody(required = false) SiteLink siteLink) {

        int pageSize = 10, page = 1, start;
        start = (page - 1) * pageSize + 1;

        List<SiteLink> list, totalList; //返回List中属性即可
        int total = 0;
        if (null == siteLink) {
            SiteLink params = new SiteLink();
            list = siteLinkMapper.getLink(params);
        } else {
            Integer offset = (siteLink.getPage() - 1) * siteLink.getPageSize();
            siteLink.setOffset(offset);
            list = siteLinkMapper.getLink(siteLink);
        }
        totalList = siteLinkMapper.getLink(null);
        total = totalList.size();
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("code", 200);
        map.put("data", list);
        return map;
    }
}
